class SiteController < ApplicationController

    before_filter :account_is_logged_in, :only => [:site_new, :site_create]

    layout "site",  :except => :images 
    
    def index
        list
        render :action => 'list'
    end
    
    # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
    verify :method => :post, :only => [ :destroy, :create, :update ],
    :redirect_to => { :action => :list }
    
    def site_home
        redirect_to :action => 'site_show', :site_directory => @site
    end
    
    def site_search
        @search = true
        @site_pages, @sites = paginate :sites, :per_page => 10
        @sites.delete @site  #don't show the home site
    end  
    
    def site_show
        if !params[:page_title] && params[:site_directory] == HOME_SITE
        	@search = true    
        end
        if @site
            @page = @site.get_page params[:page_title]
            if !@page
                render :controller => 'site', :action => 'site_no_page' 
            end
        else
            render :controller => 'site', :action => 'site_not_found'
        end
    end
    
    def site_new
        @newsite = Site.new
    end
    
    def site_create
        @newsite = Site.new(params[:newsite])
        user = User.find_first(["username = ?", @account.login])
        @newsite.users.push_with_attributes(user, :role_id => Role.admin.id)
        
        if @newsite.save
            flash[:notice] = 'Site was successfully created.'
            redirect_to :action => 'site_list'
        else
            render :action => 'site_new'
        end
    end 
    
    def properties_edit
        @newsite = @site
    end
    
    def properties_update
        if @site.update_attributes(params[:newsite])
            flash[:notice] = 'Site was successfully updated.'
            redirect_to :action => 'site_show', :site_directory => @site
        else
            render :action => 'properties_edit'
        end
    end
    
    def destroy
        Site.find(params[:id]).destroy
        redirect_to :action => 'list'
    end
    
    private
    def create_if_missing *names
    	names.each do |name| Dir.mkdir(name) unless File.directory?(name) end
    end
    
end
